package me.firstapp.weixin.controller.pay;

import java.math.RoundingMode;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.mp.WeixinProxy;
import com.foxinmy.weixin4j.mp.api.TmplApi;
import com.foxinmy.weixin4j.mp.message.TemplateMessage;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.utils.DateUtils;
import me.firstapp.common.utils.ResponseUtils;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.common.utils.SystemConfig;
import me.firstapp.common.utils.WeiXinConfig;
import me.firstapp.module.weixin.member.Member;
import me.firstapp.module.weixin.order.ProductOrder;
import me.firstapp.module.weixin.transfer.TransferMemberProduct;
import me.firstapp.module.weixin.transfer.TransferMemberRecord;
import me.firstapp.service.weixin.activity.RedPackRecordService;
import me.firstapp.service.weixin.member.MemberService;
import me.firstapp.service.weixin.product.ProductOrderService;
import me.firstapp.service.weixin.transfer.TransferMemberProductService;
import me.firstapp.service.weixin.transfer.TransferMemberRecordService;
import me.firstapp.weixin.controller.base.BaseController;

@Controller
public class BeiBiPayController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(BeiBiPayController.class);

	@Autowired
	private ProductOrderService productOrderService;

	@Autowired
	private MemberService memberService;

	@Autowired
	private WeixinProxy weixinProxy;

	@Autowired
	private RedPackRecordService redPackRecordService;

	@Autowired
	private TransferMemberRecordService transferMemberRecordService;

	@Autowired
	private TransferMemberProductService transferMemberProductService;

	@RequestMapping("/page/beiBiPay.do")
	public void beiBiPay(String orderNo, HttpServletRequest request, HttpServletResponse response) {
		logger.info("贝币支付接口开始被调用，请求参数orderNo=" + orderNo);
		SingleObject<Object> result = new SingleObject<>();
		try {
			String openId = getCurrentLoginOpenId(request, response);
			Member member = memberService.findMemberByOpenId(openId);
			if (null == member) {
				throw new ServiceException(StatusHouse.STATUS_PAGE_ERROR_NOT_CONCERN_WEIXIN);
			}
			if (StrUtils.isNULL(orderNo)) {
				logger.error("订单号是空的");
				throw new ServiceException(StatusHouse.COMMON_PARAMETER_ERROR);
			}
			String orderType = orderNo.substring(0, 1);
			if (ProductOrder.ORDER_NO_START.equals(orderType)) {// 商品订单
				ProductOrder productOrder = productOrderService.findByOrderNo(openId, orderNo);
				if (null == productOrder) {
					logger.error("订单【" + orderNo + "】存在");
					throw new ServiceException(StatusHouse.STATUS_ORDER_NOT_EXIST);
				}
				if (ProductOrder.STATUS_NOT_PAY != productOrder.getStatus()) {
					logger.error("订单【" + orderNo + "】不是未支付状态");
					throw new ServiceException("error", "订单状态异常");
				}
				productOrder = productOrderService.executeBeiBiPay(productOrder, member);
				if (ProductOrder.STATUS_PAYED == productOrder.getStatus()) {
					productOrderService.executeGivePoint(productOrder);
					// 红包商品只能兑换一次记录
					if (1603 == productOrder.getProductId()) {
						redPackRecordService.executeAddRedPackRecord(productOrder);
					}
					try {
						TemplateMessage tplMessage = new TemplateMessage(productOrder.getOpenId(),
								WeiXinConfig.WEIXIN_BUY_SUCCESS_TEMPLATE_ID,
								SystemConfig.mServerUrl + "/page/productOrderDetailView.htm?orderNo=" + orderNo);
						tplMessage.pushHead("").pushTail("")
								.pushItem("first", member.getName() + "，您购买的【" + productOrder.getName() + "】支付成功啦")
								.pushItem("keyword1", productOrder.getOrderNo())
								.pushItem("keyword2", productOrder.getCounts() + "")
								.pushItem("keyword3",
										productOrder.getPayAmount().setScale(2, RoundingMode.HALF_UP).toString() + "贝币")
								.pushItem("keyword4",
										productOrder.getGivePoint().setScale(4, RoundingMode.HALF_UP).toString() + "积分")
								.pushItem("remark", "若需帮助请联系客服，欢迎再次光临！");
						TmplApi tmplApi = new TmplApi(weixinProxy.getTokenManager());
						String sendResult = tmplApi.sendTmplMessage(tplMessage);
						System.out.println(
								"消息模板【" + WeiXinConfig.WEIXIN_BUY_SUCCESS_TEMPLATE_ID + "】发送消息返回结果：" + sendResult);
						logger.info("消息模板【" + WeiXinConfig.WEIXIN_BUY_SUCCESS_TEMPLATE_ID + "】发送消息返回结果：" + sendResult);
					} catch (WeixinException e1) {
						e1.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					throw new ServiceException("error", "支付失败!");
				}
			} else if (TransferMemberRecord.RECORD_NO_START.equals(orderType)) {// 用户转让订单
				TransferMemberRecord transferMemberRecord = transferMemberRecordService.findByOpenIdAndRecordNo(openId,
						orderNo);
				transferMemberRecord = transferMemberRecordService.executeBeiBiPay(transferMemberRecord, member);
				if (TransferMemberRecord.STATUS_COMPLETE == transferMemberRecord.getStatus()) {
					// 订单完成
					try {
						// 给买家发送通知
						TemplateMessage tplMessage = new TemplateMessage(openId,
								WeiXinConfig.WEIXIN_TRANSFER_MEMBER_TEMPLATE_ID,
								SystemConfig.mServerUrl + "/page/memberFansPage.htm");
						tplMessage.pushHead("").pushTail("")
								.pushItem("first",
										member.getName() + "，您已成功接收" + transferMemberRecord.getCounts() + "个用户")
								.pushItem("keyword1", transferMemberRecord.getRecordNo())
								.pushItem("keyword2", DateUtils.getNowStr("yyyy-MM-dd HH:mm:ss"))
								.pushItem("remark", "若需帮助请联系客服");
						TmplApi tmplApi = new TmplApi(weixinProxy.getTokenManager());
						String sendResult = tmplApi.sendTmplMessage(tplMessage);
						logger.info(
								"消息模板【" + WeiXinConfig.WEIXIN_TRANSFER_MEMBER_TEMPLATE_ID + "】发送消息返回结果：" + sendResult);

						// 给卖家发送通知
						TransferMemberProduct transferMemberProduct = transferMemberProductService
								.findById(transferMemberRecord.getTransferMemberProductId());
						TemplateMessage tplMessage2 = new TemplateMessage(transferMemberProduct.getOwnOpenId(),
								WeiXinConfig.WEIXIN_TRANSFER_MEMBER_TEMPLATE_ID, "");
						Member ownMember = memberService.findMemberByOpenId(transferMemberProduct.getOwnOpenId());
						tplMessage2.pushHead("").pushTail("")
								.pushItem("first",
										ownMember.getName() + "，您转让的" + transferMemberRecord.getCounts()
												+ "个用户已成功被买家接收")
								.pushItem("keyword1", transferMemberRecord.getRecordNo())
								.pushItem("keyword2", DateUtils.getNowStr("yyyy-MM-dd HH:mm:ss"))
								.pushItem("remark", "您设置的费用【" + transferMemberProduct.getAmount() + "贝币】已进入您的贝币账户。");
						TmplApi tmplApi2 = new TmplApi(weixinProxy.getTokenManager());
						String sendResult2 = tmplApi2.sendTmplMessage(tplMessage2);
						logger.info(
								"消息模板【" + WeiXinConfig.WEIXIN_TRANSFER_MEMBER_TEMPLATE_ID + "】发送消息返回结果：" + sendResult2);
					} catch (WeixinException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}

				}
			} else {
				throw new ServiceException(StatusHouse.STATUS_ORDER_NOT_EXIST);
			}
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			logger.info("订单【" + orderNo + "】支付完成");
		} catch (ServiceException e) {
			logger.error("订单【" + orderNo + "】支付失败！", e);
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			logger.error("订单【" + orderNo + "】支付失败！", e);
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}
}
